package com.example.forum.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.UserMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.utils.MD5Util;
import com.example.forum.utils.StringUtil;
import com.example.forum.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper ;
    @Override
    public void createUser(User user) {
        // 1.非空校验
        if (user == null || StringUtil.isEmpty(user.getUsername()) || StringUtil.isEmpty(user.getSalt()) ||
                StringUtil.isEmpty(user.getPassword()) || StringUtil.isEmpty(user.getNickname())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 2.根据用户名查询用户是否存在
        User exist = userMapper.selectByUsername(user.getUsername());
        if (exist != null) {
            // 用户存在
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }

        // 3.设置默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        // 4.插入数据库
        int row = userMapper.insert(user);
        if (row != 1) {
            log.info(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        log.info("新增用户成功 , username = " + user.getUsername());
    }

    @Override
    public User selectByUsername(String username) {
        if (StringUtil.isEmpty(username) ) {
            // 校验密码
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByUsername(username);
        return user;
    }

    @Override
    public User login(String username, String password) {
        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
            // 1.校验参数1
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 2.接收用户 用户为空的话不能登录 -- 尝试跳转到注册页面还是
        User user = selectByUsername(username);
        if (user == null) {
            log.warn(ResultCode.FAILED_USER_NOTEXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOTEXISTS));
        }
        // 3.校验密码和保存的密码是否一致
        String salt = user.getSalt();
        String ciphertext = MD5Util.md5Salt(password,salt);
        if (!ciphertext.equals(user.getPassword())) {
            log.warn(ResultCode.FAILED_LOGIN.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        return user;
    }

    @Override
    public User selectById(Long id) {
        if (id == null) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() + 1);
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + " 实际受影响行数 : " + row);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    /**
     * 用户发表帖子数-1
     * @param id 用户id
     */
    @Override
    public void subOneArticleCountById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        // 用户处于禁言状态也可以删除自己发表的帖子
        if (user == null) {
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() - 1);
        updateUser.setUpdateTime(new Date());
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + " 实际受影响行数 : " + row);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyInfo(User user) {
        if (user == null || user.getId() == null || user.getId() <= 0) {
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        User existUser = userMapper.selectByPrimaryKey(user.getId());
        if ( existUser == null  ||  existUser.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOTEXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOTEXISTS));
        }
        // 通过标志位校验参数是否为空,当有一个参数不为空时,将标志位置为true
        boolean checkAttr = false ; // false表示没有通过 , 即所有参数都为空
        User updateUser = new User();
        updateUser.setId(user.getId());
        if (!StringUtil.isEmpty(user.getUsername())
        && !user.getUsername().equals(existUser.getUsername())) {
            // 需要更新用户名时,需要尽心唯一性的校验
            User checkUser = userMapper.selectByUsername(user.getUsername());
            if (checkUser != null) {
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }
            updateUser.setUsername(user.getUsername());
            checkAttr = true;
        }
        if (!StringUtil.isEmpty(user.getNickname())
        && !user.getNickname().equals(existUser.getNickname())) {
            // 昵称不一样并且不为空才要更新
            updateUser.setNickname(user.getNickname());
            checkAttr = true;
        }

        if (user.getGender()!=null
                && existUser.getGender()!= user.getGender()) {
            updateUser.setGender(user.getGender());
            if (updateUser.getGender() > 2 || updateUser.getGender() < 0) {
                updateUser.setGender((byte)2);
            }
            checkAttr = true;
        }

        if (!StringUtil.isEmpty(user.getEmail())
                && !user.getEmail().equals(existUser.getEmail())) {
            // 昵称不一样并且不为空才要更新
            updateUser.setEmail(user.getEmail());
            checkAttr = true;
        }

        if (!StringUtil.isEmpty(user.getPhoneNum())
                && !user.getPhoneNum().equals(existUser.getPhoneNum())) {
            // 昵称不一样并且不为空才要更新
            updateUser.setPhoneNum(user.getPhoneNum());
            checkAttr = true;
        }
        if (!StringUtil.isEmpty(user.getRemark())
                && !user.getRemark().equals(existUser.getRemark())) {
            // 昵称不一样并且不为空才要更新
            updateUser.setRemark(user.getRemark());
            checkAttr = true;
        }
        if (checkAttr == false) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + "实际影响行数为" + row);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        log.info("修改成功");
    }

    /**
     * 修改密码
     * @param id  用户id
     * @param newPassword  新密码
     * @param oldPassword  旧密码
     */
    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        if (StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(oldPassword)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null || user.getDeleteState() == 1) {
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }

        String oldPasswordCipher = MD5Util.md5Salt(oldPassword,user.getSalt());
        if (!oldPasswordCipher.equalsIgnoreCase(user.getPassword())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 用户存在 切状态正常 切密码都不为空
        if (newPassword.equals(oldPassword)) {
            log.warn("新密码和旧密码一样");
            throw new ApplicationException(AppResult.failed("新密码和旧密码一样"));
        }
        // 验证密码是否正确

        String salt = UUIDUtil.UUID_32();
        User updateUser = new User();
        updateUser.setId(user.getId());
        String cipherText = MD5Util.md5Salt(newPassword , salt);
        updateUser.setSalt(salt);
        updateUser.setPassword(cipherText);
        updateUser.setUpdateTime(new Date());
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + " 实际受影响行数 : " + row);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }
}
